# coding: utf-8

import json
from io import BytesIO

import time

from fraMail.framail import FraMail

import QRcodeOper

from settings import *
from dbproxy.dbproxy import *

from globalsettings import CUR_MODE

if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *
LOG = getFileLog()
log = LOG


#
# 根据bd或无,查询所属公司列表--重复
# 根据,查询全部报告模板--重复
# 根据标准组卷类型,查询标准组卷模板--重复
# 根据无或客户id,查询客户题目 --重复
# 保存客户问卷生成二维码:主要作用ocean的scoring(question_id),和rules的scoring(question_id和rule_id)


class CustomerCombine(object):
    """
    客户题库相关操作的接口功能均封装在此
    """
    table_name = 'surveys_collection'

    def __init__(self):
        super(CustomerCombine, self).__init__()
        self.db_proxy = DBProxy(db=mongo)

    def _get_report_type(self, report_code):
        if report_code is None:
            LOG.error('report_code未指定')
            return None
        ret = self.db_proxy.query_one(table='desc_collection', query={'code': report_code})
        if ret.get('count') <= 0:
            LOG.error('未查到 %s 对应的记录' % report_code)
            return None
        data = ret.get('data')
        if data is None:
            LOG.error('获取数据出错')
            return None
        data = data[0]

        report_type = data.get('type')

        return report_type

    def query_survey(self, pagesize, page, company_id=None, survey_id=None, ):
        """
        根据题号 题目属性 查找问卷模板 (仅仅模型问卷模板)
        :param pagesize
        :param page
        :return:
        """
        log.debug('查询')
        log.debug('查询模型题库')
        if survey_id is None and company_id is not None:
            ret = self.db_proxy.page_query(table=self.table_name,
                                           query={'company_id': company_id},
                                           page=page, pagesize=pagesize)

        if survey_id is not None:
            ret = self.db_proxy.page_query(table=self.table_name, query={'survey_id': survey_id},
                                           page=page, pagesize=pagesize)
        if survey_id is None and company_id is None:
            ret = self.db_proxy.page_query(table=self.table_name,
                                           query={'survey_type': 3},
                                           page=page, pagesize=pagesize)

        log.debug('查询成功返回')
        return ret

    def query_detail(self, survey_id):
        log.debug(' : %s' % (survey_id))
        ret = self.db_proxy.query_one(table=self.table_name, query={'survey_id': survey_id})
        log.debug(' ')
        return ret

    def query_detail_by_code(self, code):
        log.debug(' : %s' % (code))
        ret = self.db_proxy.query_one(table=self.table_name, query={'code': code})
        log.debug(' ')
        return ret

    def edit(self, survey_id, setvalue, insert_not_found=False):
        log.debug(' ')
        ret = self.db_proxy.update(table=self.table_name, query={'survey_id': survey_id}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        return ret

    def query_default_tempsurvey(self, survey_code):
        log.debug(' : %s' % (survey_code))
        ret = self.db_proxy.query_one(table='t_company_surveytemp', query={'survey_code': survey_code})
        log.debug('查询公司特定默认问卷模板 ')  # survey_code
        return ret

    def query_otherdefault_tempsurvey(self, pcompany):
        log.debug(' : %s' % (pcompany))
        ret = self.db_proxy.query_one(table='t_company_surveytemp', query={'p_company_id': pcompany})
        if len(ret.get('data')) <= 0:
            ret = self.db_proxy.query_one(table='t_company_surveytemp', query={'can_use4other': 1, 'default': 999})
        log.debug('查询公司默认问卷模板 ')  # survey_code
        return ret

    def insert(self, value):
        log.debug('插入客户组卷')
        last_item = self.db_proxy.query_lastone(table=self.table_name, field="survey_id")
        if len(last_item['data']) > 0:
            value["survey_id"] = last_item['data'][0]["survey_id"] + 1
        else:
            value["survey_id"] = 1
        # value['$inc'] = {'survey_id': 1}
        report_code = value.get('report_code')
        report_type = self._get_report_type(report_code)
        value['report_type'] = report_type
        LOG.debug('report_type is %s' % report_type)
        longurl = COMBINE_LONGURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code']) \
            .replace("{$stat$}", COMBINE_STAT).replace("{$url_title$}", value['url_title'])
        shorturl = COMBINE_SHORTURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code'])
        nowxlongurl = COMBINE_NOWXLONGURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code']) \
            .replace("{$nowxstat$}", COMBINE_NOWXSTAT).replace("{$url_title$}", value['url_title'])
        nowxshorturl = COMBINE_NOWXSHORTURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code'])
        shorturlmap = '/' + value['code']
        shorturlnowxmap = '/' + value['code'] + '_nowx'
        value['longurl'] = longurl
        value['shorturl'] = shorturl
        value['nowxlongurl'] = nowxlongurl
        value['nowxshorturl'] = nowxshorturl
        value['shorturlmap'] = shorturlmap
        value['shorturlnowxmap'] = shorturlnowxmap
        ret = self.db_proxy.insert(table=self.table_name, value=value)
        ret['survey_id'] = value['survey_id']
        ret['longurl'] = longurl
        ret['shorturl'] = shorturl
        ret['nowxlongurl'] = nowxlongurl
        ret['nowxshorturl'] = nowxshorturl
        ret['shorturlmap'] = shorturlmap
        ret['shorturlnowxmap'] = shorturlnowxmap
        if ret['code'] == 200:
            shorlongdict = {}
            shorlongdict2 = {}
            shorlongdict['longurl'] = longurl
            shorlongdict['shorturl'] = shorturlmap
            shorlongdict2['longurl'] = nowxlongurl
            shorlongdict2['shorturl'] = shorturlnowxmap
            self.db_proxy.update(table='short_longurl_collection', query={'shorturl': shorturlmap},
                                 setvalue=shorlongdict,
                                 insert_not_found=True)
            self.db_proxy.update(table='short_longurl_collection', query={'shorturl': shorturlnowxmap},
                                 setvalue=shorlongdict2,
                                 insert_not_found=True)
        return ret

    def insertBXJJR(self, value):
        log.debug('插入客户组卷')
        last_item = self.db_proxy.query_lastone(table=self.table_name, field="survey_id")
        if len(last_item['data']) > 0:
            value["survey_id"] = last_item['data'][0]["survey_id"] + 1
        else:
            value["survey_id"] = 1
        # value['$inc'] = {'survey_id': 1}
        report_code = value.get('report_code')
        report_type = self._get_report_type(report_code)
        value['report_type'] = report_type
        LOG.debug('report_type is %s' % report_type)
        longurl = COMBINE_LONGURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code']) \
            .replace("{$stat$}", COMBINE_STAT).replace("{$url_title$}", value['url_title'])
        shorturl = COMBINE_SHORTURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code'])
        nowxlongurl = COMBINE_NOWXLONGURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code']) \
            .replace("{$nowxstat$}", COMBINE_NOWXSTAT).replace("{$url_title$}", value['url_title'])
        nowxshorturl = COMBINE_NOWXSHORTURL.replace("{$hostname$}", COMBINE_HOSTNAME).replace("{$code$}", value['code'])
        shorturlmap = '/' + value['code']
        shorturlnowxmap = '/' + value['code'] + '_nowx'
        value['longurl'] = longurl
        value['shorturl'] = shorturl
        value['nowxlongurl'] = nowxlongurl
        value['nowxshorturl'] = nowxshorturl
        value['shorturlmap'] = shorturlmap
        value['shorturlnowxmap'] = shorturlnowxmap
        ret = self.db_proxy.insert(table=self.table_name, value=value)
        ret['survey_id'] = value['survey_id']
        ret['longurl'] = longurl
        ret['shorturl'] = shorturl
        ret['nowxlongurl'] = nowxlongurl
        ret['nowxshorturl'] = nowxshorturl
        ret['shorturlmap'] = shorturlmap
        ret['shorturlnowxmap'] = shorturlnowxmap
        if ret['code'] == 200:
            shorlongdict = {}
            shorlongdict2 = {}
            shorlongdict['longurl'] = longurl
            shorlongdict['shorturl'] = shorturlmap
            shorlongdict2['longurl'] = nowxlongurl
            shorlongdict2['shorturl'] = shorturlnowxmap
            self.db_proxy.update(table='short_longurl_collection', query={'shorturl': shorturlmap},
                                 setvalue=shorlongdict,
                                 insert_not_found=True)
            self.db_proxy.update(table='short_longurl_collection', query={'shorturl': shorturlnowxmap},
                                 setvalue=shorlongdict2,
                                 insert_not_found=True)
        return ret

    def delete(self, survey_id):
        log.debug(' : %s' % (survey_id))
        ret = self.db_proxy.delete(table=self.table_name, query={'survey_id': survey_id})
        return ret

    def query_desc_collection(self, pagesize, page, code=None, survey_id=None, ):
        """
        根据题号 题目属性 查找问卷模板 (仅仅模型问卷模板)
        :param pagesize
        :param page
        :return:
        """
        log.debug('查询')
        log.debug('查询报告模板内容')
        ret = self.db_proxy.page_query(table='desc_collection',
                                       query={'code': code},
                                       page=1, pagesize=5)
        log.debug('查询成功返回')
        return ret

    def insert4BXJJR(self, value):

        '''
        新增保险问卷 fro BXJJR 保险经纪人项目
        无跳转规则问卷
        输入:survey_id等问卷表字段属性
        返回:ret集合,ret.code=200成功
        :return:
        '''
        log.debug('创建默认问卷')
        # value = get_param(request)
        # 根据report_code生成report_type
        # 根据code查询引用模板, select_survey_code
        # 查询引用的模板是标准的话 ,添加 OCEAN_scoring 中,获取questions替换原questions中的[]
        # 查询引用的模板是特征的话 ,添加 rule_scoring 中,获取questions替换原questions中的[]
        # docode = value.get('code')
        # code = job_name + create_4random_pwd(codelen=6)
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        # docompanyid = value.get('company_id')
        user = value.get('user')

        code = 'BXJJR'  # value.get('select_survey_code')
        getret = customer_combine.query_detail_by_code(code=code)
        if len(getret['data']) == 0:
            return json.dumps(getret)
        row = getret.get('data')[0]
        docode = code + '-' + user
        value['code'] = docode
        value['company_id'] = docode
        value['select_survey_type'] = row.get('select_survey_type')
        value['survey_type'] = row.get('survey_type')
        value['report_type'] = 'insure'
        value['report_code'] = 'insure'
        value['url_title'] = '保险经纪人'
        value['survey_type'] = 2
        value['survey_version'] = 2  # 新的混合问卷算法特征模型计算
        value['p_company_id'] = docode
        value['company_id'] = docode
        value['job_cname'] = docode
        value['job_name'] = docode
        value['select_survey_code'] = code
        macroquestions = row.get('questions')
        if value['select_survey_type'] == 10:
            value['O_scoring'] = row.get('O_scoring')
            value['C_scoring'] = row.get('C_scoring')
            value['E_scoring'] = row.get('E_scoring')
            value['A_scoring'] = row.get('A_scoring')
            value['N_scoring'] = row.get('N_scoring')
            value['O_norm_mean'] = row.get('O_norm_mean')
            value['C_norm_mean'] = row.get('C_norm_mean')
            value['E_norm_mean'] = row.get('E_norm_mean')
            value['A_norm_mean'] = row.get('A_norm_mean')
            value['N_norm_mean'] = row.get('N_norm_mean')
            value['O_norm_SD'] = row.get('O_norm_SD')
            value['C_norm_SD'] = row.get('C_norm_SD')
            value['E_norm_SD'] = row.get('E_norm_SD')
            value['A_norm_SD'] = row.get('A_norm_SD')
            value['N_norm_SD'] = row.get('N_norm_SD')
        if value['select_survey_type'] == 1:
            value['rule_scoring'] = row.get('questions')
        if value.get('questions') is not None:
            questions = value.get('questions').split(',')
            for key in questions:  # each
                if not str(key).isdigit():
                    value['questions'] = str(value['questions']).replace(key, macroquestions)
                    break
        else:
            value['questions'] = macroquestions
        value['title'] = '保险经纪人问卷'
        value['description'] = '保险经纪人模板问卷,自动生成'
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        value['create_time'] = timestr
        ret = customer_combine.insertBXJJR(value=value)
        print(ret)
        ret['survey_code'] = docode
        return ret


customer_combine = CustomerCombine()


# @app.route('/custom/all_question', methods=['GET','OPTIONS'])
# def handler_all_questions():
#    """
#    查询用户题库
#    :return:
#    """
#    company_id = request.args.get('company_id')
#    log.info('公司ID：%s'%(company_id))
#    return json.dumps(customer_question.query_all_questions_by(company_id=company_id, pagesize=500, page=1))


@app.route('/cc/getqr', methods=['GET', 'POST'])
def cc_getqr():
    '''
    获取qr图像
    输入:url 建议post请求以便支持特殊字符
    返回:response jpeg文件流返回
    :return:
    '''
    global cache_questionid_ruleid
    param = get_param(request)
    str = param.get('url')
    img = QRcodeOper.returnqrcode(str)
    msstream = BytesIO()
    img.save(msstream, "jpeg")
    img.close()
    # response = make_response(msstream.getvalue())
    # response.headers['Content-Type'] = 'image/jpg'
    resp = Response(msstream.getvalue(), mimetype="image/jpeg")
    print(cache_questionid_ruleid)
    return resp


@app.route('/cc/refresh', methods=['GET', 'POST'])
def cc_refresh():
    '''
    刷新全局缓存
    输入:无
    返回:'ok'
    :return:
    '''
    global cache_questionid_ruleid
    rows = MongoOper.pagequery(mongo, table='desc_collection', query={}, page=1, pagesize=0)
    for row in rows['data']:
        code = row.get('code')
        if code is None:
            continue
        if desc_map.get(code) is None:
            desc_map[code] = {}
        if row['id'] == 'o':
            desc_map[code]['o'] = row
        if row['id'] == 'c':
            desc_map[code]['c'] = row
        if row['id'] == 'e':
            desc_map[code]['e'] = row
        if row['id'] == 'a':
            desc_map[code]['a'] = row
        if row['id'] == 'n':
            desc_map[code]['n'] = row
    rows = MongoOper.pagequery(mongo, table='questions_collection', query={}, page=1, pagesize=0)
    for row in rows.get('data'):
        if row.get('rule_id') is not None:
            cache_questionid_ruleid[row.get('question_id')] = row.get('rule_id')
    return make_response('ok')


# @app.route('/custombin/xxxx', methods=['GET', 'POST', 'OPTIONS'])
# @verify_token
# def h_xxxx():
#     log.debug('查询公司')
#     param = get_param(request)
#     return json.dumps(customer_combine.get_company(param))


@app.route('/cc/query_survey', methods=['GET', 'POST'])
@verify_token
def cc_query_survey():
    '''
    根据问卷号 公司号 查找问卷模板 (仅仅客户问卷模板)
    输入:survey_id company_id 或者不输入查询客户类型问卷
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    company_id = param.get('company_id')
    survey_id = param.get('survey_id')
    return json.dumps(customer_combine.query_survey(pagesize=0, page=1, company_id=company_id, survey_id=survey_id))


@app.route('/cc/query_detail', methods=['GET', 'POST'])
@verify_token
def cc_query_detail():
    '''
    查询单个问卷模板
    输入:survey_id
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    survey_id = param.get('survey_id')
    return json.dumps(customer_combine.query_detail(survey_id=survey_id))


@app.route('/cc/edit', methods=['GET', 'POST'])
@verify_token
def cc_edit():
    '''
    编辑问卷
    输入:survey_id等问卷表字段属性
    返回:ret集合,ret.code=200成功
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    survey_id = param.get('survey_id')
    del param['token']

    if param.get('monitor_mail') is not None:
        # 发送二维码链接
        get_one = customer_combine.query_detail(survey_id=survey_id)
        survey_obj = get_one['data'][0]
        str = survey_obj['shorturl']
        log.info(str)
        img = QRcodeOper.returnqrcode(str)
        msstream = BytesIO()
        img.save(msstream, "jpeg")
        img.close()
        mail = FraMail()
        mail.login()
        mail.send_qrfile(filename=msstream.getvalue(), to=param.get('monitor_mail'), title='问卷二维码图片链接',
                         msg='这是二维码图片链接邮件,请查看附件图片')

    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    param['update_time'] = timestr
    return json.dumps(customer_combine.edit(survey_id=survey_id, setvalue=param))


@app.route('/cc/insert', methods=['GET', 'POST'])
@verify_token
def cc_insert():
    '''
    新增问卷
    输入:survey_id等问卷表字段属性
    返回:ret集合,ret.code=200成功
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    value = param
    #
    # 根据report_code生成report_type
    #

    del value['token']
    # 根据code查询引用模板, select_survey_code
    # 查询引用的模板是标准的话 ,添加 OCEAN_scoring 中,获取questions替换原questions中的[]
    # 查询引用的模板是特征的话 ,添加 rule_scoring 中,获取questions替换原questions中的[]
    code = value.get('select_survey_code')
    getret = customer_combine.query_detail_by_code(code=code)
    # 前台只传了name,根据name获取company_id
    ret_company = MongoOper.pagequery(mongo, table='company_collection', query={'company_name': value['company_id']})
    if len(ret_company['data']) > 0:
        value['company_id'] = ret_company['data'][0]['guid']
    if len(getret['data']) == 0:
        return json.dumps(getret)
    row = getret.get('data')[0]
    macroquestions = row.get('questions')
    if value['select_survey_type'] == 0:
        value['O_scoring'] = row.get('O_scoring')
        value['C_scoring'] = row.get('C_scoring')
        value['E_scoring'] = row.get('E_scoring')
        value['A_scoring'] = row.get('A_scoring')
        value['N_scoring'] = row.get('N_scoring')
        value['O_norm_mean'] = row.get('O_norm_mean')
        value['C_norm_mean'] = row.get('C_norm_mean')
        value['E_norm_mean'] = row.get('E_norm_mean')
        value['A_norm_mean'] = row.get('A_norm_mean')
        value['N_norm_mean'] = row.get('N_norm_mean')
        value['O_norm_SD'] = row.get('O_norm_SD')
        value['C_norm_SD'] = row.get('C_norm_SD')
        value['E_norm_SD'] = row.get('E_norm_SD')
        value['A_norm_SD'] = row.get('A_norm_SD')
        value['N_norm_SD'] = row.get('N_norm_SD')
    if value['select_survey_type'] == 1:
        value['rule_scoring'] = row.get('questions')
    if value['select_survey_type'] == 10:
        value['survey_version'] = 2
        value['rule_scoring'] = row.get('questions')
        value['O_scoring'] = row.get('O_scoring')
        value['C_scoring'] = row.get('C_scoring')
        value['E_scoring'] = row.get('E_scoring')
        value['A_scoring'] = row.get('A_scoring')
        value['N_scoring'] = row.get('N_scoring')
        value['O_norm_mean'] = row.get('O_norm_mean')
        value['C_norm_mean'] = row.get('C_norm_mean')
        value['E_norm_mean'] = row.get('E_norm_mean')
        value['A_norm_mean'] = row.get('A_norm_mean')
        value['N_norm_mean'] = row.get('N_norm_mean')
        value['O_norm_SD'] = row.get('O_norm_SD')
        value['C_norm_SD'] = row.get('C_norm_SD')
        value['E_norm_SD'] = row.get('E_norm_SD')
        value['A_norm_SD'] = row.get('A_norm_SD')
        value['N_norm_SD'] = row.get('N_norm_SD')
    if value.get('questions') is not None:
        questions = value.get('questions').split(',')
        for key in questions:  # each
            if not str(key).isdigit():
                value['questions'] = str(value['questions']).replace(key, macroquestions)
                break
    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    value['create_time'] = timestr
    return json.dumps(customer_combine.insert(value=value))  # value.code


@app.route('/cc/insert4bole', methods=['GET', 'POST'])
def cc_insert4bole():
    '''
    新增问卷 fro bole
    输入:survey_id等问卷表字段属性
    返回:ret集合,ret.code=200成功
    :return:
    '''
    log.debug(' ')
    value = get_param(request)
    #
    # 根据report_code生成report_type
    #
    if value.get('token') != 'tokenhuayuan':
        return json.dumps(g_ret)
    del value['token']
    # 根据code查询引用模板, select_survey_code
    # 查询引用的模板是标准的话 ,添加 OCEAN_scoring 中,获取questions替换原questions中的[]
    # 查询引用的模板是特征的话 ,添加 rule_scoring 中,获取questions替换原questions中的[]
    docode = value.get('code')
    docompanyid = value.get('company_id')
    code = 'BOLE34'  # value.get('select_survey_code')
    getret = customer_combine.query_detail_by_code(code=code)
    if len(getret['data']) == 0:
        return json.dumps(getret)
    row = getret.get('data')[0]
    value['select_survey_type'] = row.get('survey_type')
    value['report_type'] = 'hr'
    value['report_code'] = 'bole'
    macroquestions = row.get('questions')
    if value['select_survey_type'] == 0:
        value['O_scoring'] = row.get('O_scoring')
        value['C_scoring'] = row.get('C_scoring')
        value['E_scoring'] = row.get('E_scoring')
        value['A_scoring'] = row.get('A_scoring')
        value['N_scoring'] = row.get('N_scoring')
        value['O_norm_mean'] = row.get('O_norm_mean')
        value['C_norm_mean'] = row.get('C_norm_mean')
        value['E_norm_mean'] = row.get('E_norm_mean')
        value['A_norm_mean'] = row.get('A_norm_mean')
        value['N_norm_mean'] = row.get('N_norm_mean')
        value['O_norm_SD'] = row.get('O_norm_SD')
        value['C_norm_SD'] = row.get('C_norm_SD')
        value['E_norm_SD'] = row.get('E_norm_SD')
        value['A_norm_SD'] = row.get('A_norm_SD')
        value['N_norm_SD'] = row.get('N_norm_SD')
    if value['select_survey_type'] == 1:
        value['rule_scoring'] = row.get('questions')
    if value.get('questions') is not None:
        questions = value.get('questions').split(',')
        for key in questions:  # each
            if not str(key).isdigit():
                value['questions'] = str(value['questions']).replace(key, macroquestions)
                break
    else:
        value['questions'] = macroquestions
    value['title'] = 'bole自动测试卷'
    value['survey_type'] = 2
    value['description'] = 'bole自动测试卷,自动生成'
    value['select_survey_code'] = 'BOLE34'
    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    value['create_time'] = timestr
    return json.dumps(customer_combine.insert(value=value))  # value.code


@app.route('/cc/insert4newcompany', methods=['GET', 'POST'])
def cc_insert4newcompany(param1=None):
    '''
    新增问卷 fro new subcompany api接口调用
    输入:survey_id等问卷表字段属性
    返回:ret集合,ret.code=200成功
    :return:
    '''
    log.debug(' ')
    if param1 is None:
        value = get_param(request)
    else:
        value = param1
    p_company_id = value.get('p_company_id')
    company_id = value.get('company_id')
    code = value.get('code')
    job_cname = value.get('job_cname')
    job_name = value.get('job_name')
    #
    # 根据report_code生成report_type
    #
    if value.get('token') != 'tokenhuayuanapi':
        return json.dumps(g_ret)
    del value['token']
    # 根据code查询引用模板, select_survey_code
    # 查询引用的模板是标准的话 ,添加 OCEAN_scoring 中,获取questions替换原questions中的[]
    # 查询引用的模板是特征的话 ,添加 rule_scoring 中,获取questions替换原questions中的[]
    if value.get('p_company_id') is None:
        value['p_company_id'] = value['company_id']
    # value['job_name'] = " ".join(lazy_pinyin(value['job_cname'], style=Style.NORMAL)).strip()
    # value['job_cname'] =
    # code = job_name + create_4random_pwd(codelen=6) addjob中已经给定

    gettempsurvey = customer_combine.query_default_tempsurvey(survey_code=value.get('select_survey_code'))
    if len(gettempsurvey['data']) == 0:
        gettempsurvey = customer_combine.query_otherdefault_tempsurvey(pcompany=value.get('p_company_id'))
        if len(gettempsurvey['data']) == 0:
            return json.dumps(g_ret)
        else:
            survey_code = gettempsurvey.get('data')[0].get('survey_code')
    else:
        survey_code = gettempsurvey.get('data')[0].get('survey_code')
    getret = customer_combine.query_detail_by_code(code=survey_code)
    if len(getret['data']) == 0:
        return json.dumps(getret)
    row = getret.get('data')[0]
    value1 = row
    # value1['report_type'] = 'hr'
    value1['report_code'] = 'bole'
    value1['code'] = value.get('code')
    value1['title'] = '问卷标题'
    value1['url_title'] = ' '
    value1['survey_type'] = 2
    value1['survey_version'] = 2  # 新的混合问卷算法特征模型计算
    value1['p_company_id'] = value.get('p_company_id')
    value1['company_id'] = value.get('company_id')
    value1['job_cname'] = value.get('job_cname')
    value1['job_name'] = value.get('job_name')
    value1['description'] = '子公司自动测试卷,自动生成'
    value1['select_survey_code'] = survey_code
    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    value1['create_time'] = timestr
    return json.dumps(customer_combine.insert(value=value1))  # value.code


@app.route('/cc/delete', methods=['GET', 'POST'])
@verify_token
def cc_delete():
    '''
    删除问卷
    输入:survey_id
    返回:ret集合,ret.code=200成功
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    survey_id = param.get('survey_id')
    return json.dumps(customer_combine.delete(survey_id=survey_id))


@app.route('/cc/query_desc_collection', methods=['GET', 'POST'])
@verify_token
def cc_query_desc_collection():
    '''
    根据报告
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    code = param.get('code')
    return json.dumps(customer_combine.query_desc_collection(pagesize=5, page=1, code=code))

